package com.yupi.yuojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.yupi.yuojcodesandbox.model.ExecuteCodeRequest;
import com.yupi.yuojcodesandbox.model.ExecuteCodeResponse;
import com.yupi.yuojcodesandbox.model.ExecuteMessage;
import com.yupi.yuojcodesandbox.model.JudgeInfo;
import com.yupi.yuojcodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Java代码沙箱模板方法的实现
 */
@Slf4j
public class JavaCodeSandboxTemplate implements CodeSandbox {
    public static final String GLOBAL_CODE_DIR_NAME = "tmpCode"; //全局代码存放目录
    public static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";//全局类名
    public static final long TIME_OUT = 5000L;
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String code= executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();
        //1.把用户代码保存为文件
        File userCodefile = saveCodetoFile(code);
        //2.编译代码,得到class文件
        ExecuteMessage compileFileExecuteMessage = compileFile(userCodefile);
        System.out.println(compileFileExecuteMessage);
        //3.代码执行,得到输出结果
        List<ExecuteMessage> executeMessageList = runFile(userCodefile, inputList);
        //4.收集整理输出
        ExecuteCodeResponse outputResponse = getOutputResponse(executeMessageList);
        //5.文件清理,防止服务器空间不足
        boolean b = deleteFile(userCodefile);
        if(!b){
            log.error("deleteFile error,userCodeFilePath= {}",userCodefile.getAbsolutePath());
        }
        return outputResponse;
    }

    /**
     * 1.用户代码保存为文件
     *
     */
    public File saveCodetoFile(String code) {
        //1.把用户代码保存为文件
        String userDir = System.getProperty("user.dir");
        log.info("目录1:{}",userDir);
        String globalCodePathNmae = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        //判断全局代码目录是否存在,不存在则新建
        if (!FileUtil.exist(globalCodePathNmae)) {
            FileUtil.mkdir(globalCodePathNmae);
        }
        //把用户代码隔离存放
        String uuID = String.valueOf(UUID.randomUUID());
        String userCodeParentPath = globalCodePathNmae + File.separator + uuID;
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        System.out.println(userCodeParentPath);
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
        return userCodeFile;
    }

    /**
     * 2.编译代码,得到class文件
     */
    public ExecuteMessage compileFile(File userCodeFile) {

        String compiledCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compiledCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            System.out.println(executeMessage);
            return executeMessage;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    /**
     * 3.代码执行,得到输出结果
     * @return
     */
    public List<ExecuteMessage> runFile(File userCodeFile ,List<String> inputList){
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();

        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);
                //线程守护安全,超出睡眠时间直接杀死
                new Thread(() -> {
                    try {
                        Thread.sleep(TIME_OUT);
                        System.out.println("超时了,中断");
                        //销毁进程
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
                System.out.println(executeMessage);
                executeMessageList.add(executeMessage);
            } catch (Exception e) {
                throw new RuntimeException("代码执行异常");
            }
        }
        return executeMessageList;
    }

    /**
     * 4.收集并整理输出
     * @param executeMessageList
     * @return
     */
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outPutList = new ArrayList<>();
        //最大运行时间
        long maxTime = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(1);
                break;
            }
            outPutList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        //正常运行完成
        if (outPutList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(3);
        }
        executeCodeResponse.setOutputList(outPutList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
//        judgeInfo.setMemory();
        executeCodeResponse.setJudgeInfo(judgeInfo);

        return executeCodeResponse;
    }

    /**
     * 5.文件清理
     * @return
     */
    public boolean deleteFile(File userCodeFile){
        if (userCodeFile.getParentFile() != null) {
            String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除" + (del ? "成功" : "失败"));
            return del;
        }
        return true;
    }

    /**
     * 6.自定义异常信息类
     * @param e
     * @return
     */
    public ExecuteCodeResponse getErrorResponse(Throwable e){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        //表示代码沙箱
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }

}
